package com.cjk.console.service;

import static java.util.stream.Collectors.toList;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.cjk.console.model.GroupTree;
import com.cjk.foundation.commons.BusinessException;
import com.cjk.foundation.dao.DeviceDao;
import com.cjk.foundation.dao.GroupDao;
import com.cjk.foundation.entity.GroupEntity;
import com.cjk.foundation.orm.IdReceiver;

@Service
public class GroupServiceImpl implements GroupService {

	@Autowired
	private GroupDao groupDao;

	@Autowired
	private DeviceDao deviceDao;
	
	@Autowired
	private AdService adService;

	@Transactional
	@Override
	public Integer addGroup(Integer userId, Integer pGroupId, String name, String description) {
		GroupEntity parentGroup = getParentGroupEntity(userId, pGroupId);
		Integer rgt = groupDao.selectRgtByGroupId(parentGroup.getId(), userId);
		groupDao.updateRgt(rgt, userId);
		groupDao.updateLft(rgt, userId);
		IdReceiver<Number> receiver = new IdReceiver<Number>();
		groupDao.insertBySelect(receiver, name, description, parentGroup.getId());
		if (receiver.getId() == null) {
			return null;
		}
		// 插入默认广告模块
		adService.buildDefaultFileModule(receiver.getId().intValue());
		return receiver.getId().intValue();
	}

	@Override
	public List<GroupTree> getGroupTree(Integer userId) {
		List<GroupEntity> groupEntities = groupDao.selectAll(userId, true);
		List<GroupTree> children = new ArrayList<>();

		int lastLftId = 0;
		int lastRgtId = 0;
		for (GroupEntity groupEntity : groupEntities) {
			if (groupEntity.getLft() > lastLftId && groupEntity.getRgt() < lastRgtId) {
				continue;
			}
			GroupTree subGroup = new GroupTree();
			subGroup.setId(groupEntity.getId());
			subGroup.setName(groupEntity.getName());
			subGroup.setLft(groupEntity.getLft());
			subGroup.setRgt(groupEntity.getRgt());
			subGroup.setLvl(groupEntity.getLvl());
			subGroup.setChildren(buildSubGroups(groupEntities.stream()
					.filter(sg -> sg.getLft() > groupEntity.getLft() && sg.getRgt() < groupEntity.getRgt()).collect(toList()), subGroup));

			children.add(subGroup);
			lastLftId = groupEntity.getLft();
			lastRgtId = groupEntity.getRgt();
		}
		return children;
	}

	private static List<GroupTree> buildSubGroups(List<GroupEntity> groups, GroupTree entry) {
		List<GroupEntity> subGroups = groups.stream().filter(g -> (g.getLft().shortValue() > entry.getLft().shortValue()
				&& g.getRgt().shortValue() < entry.getRgt().shortValue() && g.getLvl().byteValue() == entry.getLvl().byteValue() + 1))
				.collect(toList());
		List<GroupTree> subGroupEntry = new ArrayList<>();
		for (GroupEntity group : subGroups) {
			GroupTree e = new GroupTree();
			e.setId(group.getId());
			e.setName(group.getName());
			e.setDescription(group.getDescription());
			e.setCreateTime(group.getCreateTime());
			e.setLft(group.getLft());
			e.setRgt(group.getRgt());
			e.setLvl(group.getLvl());
			e.setChildren(buildSubGroups(groups, e));
			subGroupEntry.add(e);

		}
		return subGroupEntry;
	}

	private GroupEntity getParentGroupEntity(Integer userId, Integer pGroupId) {
		GroupEntity parentGroup = null;
		if (pGroupId == null) {
			parentGroup = groupDao.selectRootGroup(userId);
		} else {
			parentGroup = groupDao.selectById(pGroupId);
		}
		return parentGroup;
	}

	@Override
	public List<GroupEntity> getAllGroup(Integer userId) {
		return groupDao.selectAll(userId, false);
	}

	@Transactional
	@Override
	public void delGroup(Integer groupId, Integer userId) {
		GroupEntity groupEntity = groupDao.selectById(groupId);
		if (groupEntity == null) {
			throw new BusinessException("要删除的分组不存在");
		}
		List<Integer> groupIds = groupDao.selectIdsByParentId(groupEntity.getRgt(), groupEntity.getLft(), userId);
		if (groupIds.size() != 1) {
			throw new BusinessException("要删除的分组包含子分组");
		}
		List<String> sn = deviceDao.selectSnsByGroupIdIncSub(groupId, null);
		if (!CollectionUtils.isEmpty(sn)) {
			throw new BusinessException("要删除的分组包含设备");
		}

		groupDao.delete(groupEntity.getRgt(), groupEntity.getLft(), userId);

		groupDao.updateDeleteLft(groupEntity.getRgt(), groupEntity.getLft(), userId);
		groupDao.updateDeleteRft(groupEntity.getRgt(), groupEntity.getLft(), userId);
	}

	@Override
	public void editGroup(Integer groupId, String name) {
		groupDao.update(groupId, name);
	}
}
